
<template>
  <div class="progress" @click="progressClick">
    <div class="inner-bar" ref="inner">
      <div class="progress-bar" ref="progress"> </div>
      <div class="btn-bar" ref="btn" @touchstart.prevent='progressTouchStart' @touchmove.prevent='progressTouchMove' @touchend='progressTouchEnd'></div>
    </div>
  </div>
</template>

<script>
export default {
  props: {
    percent: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      newPercent: 0,
      touchStatus: false
    }
  },
  computed: {
    rect() {
      return this.$refs.inner.getBoundingClientRect().left
    },
    innerWidth() {
      return this.$refs.inner.clientWidth
    }
  },
  watch: {
    percent(newVal) {
      if (!this.touchStatus && newVal) {
        this.offset(newVal)
      }
    }
  },
  methods: {
    offset(percent) {
      const progressWidth = this.innerWidth * percent
      const btnLeft = (this.innerWidth - 16) * percent
      this.$refs.btn.style.left = btnLeft + 'px'
      this.$refs.progress.style.width = progressWidth + 'px'
    },
    triggerPercent() {
      const percent = this.$refs.progress.clientWidth / this.innerWidth
      this.$emit('percentChange', percent)
    },
    progressClick(e) {
      const offsetWidth = e.clientX - this.rect
      this.newPercent = offsetWidth / this.innerWidth
      this.offset(this.newPercent)
      this.triggerPercent()
    },
    progressTouchStart() {
      this.touchStatus = true
    },
    progressTouchMove(e) {
      if (this.touchStatus) {
        let touchX = e.touches[0].clientX - this.rect
        if (touchX > this.innerWidth) {
          touchX = this.innerWidth
        } else if (touchX < 0) {
          touchX = 0
        }
        this.newPercent = touchX / this.innerWidth
        this.offset(this.newPercent)
      }
    },
    progressTouchEnd() {
      this.touchStatus = false
      this.triggerPercent()
    }
  }
}
</script>

<style scoped>
.progress {
  width: 100%;
  height: 30px;
}
.inner-bar {
  position: relative;
  height: 4px;
  top: 12px;
  width: 100%;
  background-color: var(--color-rgba3);
}
.progress-bar {
  width: 0;
  height: 100%;
  background-color: var(--color-theme);
}
.btn-bar {
  position: absolute;
  left: 0;
  top: -6px;
  width: 16px;
  height: 16px;
  background-color: var(--color-theme);
  border-radius: 50%;
}
</style>